<route lang="yaml">
meta:
title: 新用户注册
constant: true
layout: false
requiresAuth: false
</route>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import {ElMessage, FormInstance, FormRules} from 'element-plus'
import Copyright from '@/layouts/components/Copyright/index.vue'
import apiUser from '@/api/modules/user'

const router = useRouter()

const banner = new URL('../assets/images/login-banner.png', import.meta.url).href
const title = import.meta.env.VITE_APP_TITLE

const loading = ref(false)

// 注册表单
const registerFormRef = ref<FormInstance>()
const registerForm = ref({
  username: '',
  password: '',
  confirmPassword: ''
})

const registerRules = ref<FormRules>({
  username: [
    { required: true, trigger: 'blur', message: '请输入用户名' },
    { min: 3, max: 16, trigger: 'blur', message: '用户名长度为3到16位' }
  ],
  password: [
    { required: true, trigger: 'blur', message: '请输入密码' },
    { min: 6, max: 18, trigger: 'blur', message: '密码长度为6到18位' }
  ],
  confirmPassword: [
    { required: true, trigger: 'blur', message: '请再次输入密码' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.value.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

function handleRegister() {
  registerFormRef.value?.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        await apiUser.add({
          username: registerForm.value.username,
          password: registerForm.value.password
        })

        ElMessage.success('注册成功，请登录')
        router.push({ name: 'login' })
      } catch (error) {
        console.error(error)
      } finally {
        loading.value = false
      }
    }
  })
}

function goToLogin() {
  router.push({ name: 'login' })
}
</script>

<template>
  <div>
    <div class="bg-banner" />
    <div id="login-box">
      <div class="login-banner">
        <div class="logo" />
        <img :src="banner" class="banner">
      </div>
      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        class="login-form"
        autocomplete="off"
      >
        <div class="title-container">
          <h3 class="title">
            欢迎注册 {{ title }} ! ✨
          </h3>
        </div>
        <div>
          <el-form-item prop="username">
            <el-input
              v-model="registerForm.username"
              placeholder="用户名"
              tabindex="1"
              autocomplete="off"
            >
              <template #prefix>
                <svg-icon name="ep:user" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="registerForm.password"
              type="password"
              placeholder="密码"
              tabindex="2"
              autocomplete="off"
              show-password
              @keyup.enter="handleRegister"
            >
              <template #prefix>
                <svg-icon name="ep:lock" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="confirmPassword">
            <el-input
              v-model="registerForm.confirmPassword"
              type="password"
              placeholder="确认密码"
              tabindex="3"
              autocomplete="off"
              show-password
              @keyup.enter="handleRegister"
            >
              <template #prefix>
                <svg-icon name="ep:lock" />
              </template>
            </el-input>
          </el-form-item>
        </div>
        <el-button
          :loading="loading"
          type="primary"
          size="large"
          style="width: 100%;"
          @click.prevent="handleRegister"
        >
          立即注册
        </el-button>
        <div class="sub-link">
          <span class="text">已有账号?</span>
          <el-link type="primary" :underline="false" @click="goToLogin">
            去登录
          </el-link>
        </div>
      </el-form>
    </div>
    <Copyright />
  </div>
</template>

<style lang="scss" scoped>
[data-mode="mobile"] {
  #login-box {
    position: relative;
    width: 100%;
    height: 100%;
    top: inherit;
    left: inherit;
    transform: translateX(0) translateY(0);
    flex-direction: column;
    justify-content: start;
    border-radius: 0;
    box-shadow: none;

    .login-banner {
      width: 100%;
      padding: 20px 0;


      .banner {
        position: relative;
        right: inherit;
        width: 100%;
        max-width: 375px;
        margin: 0 auto;
        display: inherit;
        top: inherit;
        transform: translateY(0);
        z-index: -1;
      }
    }

    .login-form {
      width: 100%;
      min-height: auto;
      padding: 30px;
    }
  }

  .copyright {
    position: relative;
    bottom: 0;
    padding-bottom: 10px;
  }
}

:deep(input[type="password"]::-ms-reveal) {
  display: none;
}

.bg-banner {
  position: fixed;
  z-index: 0;
  width: 100%;
  height: 100%;
  background: radial-gradient(circle at center, var(--el-fill-color-lighter), var(--el-bg-color-page));
}

#login-box {
  display: flex;
  justify-content: space-between;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
  background-color: var(--el-bg-color);
  border-radius: 10px;
  overflow: hidden;
  box-shadow: var(--el-box-shadow);

  .login-banner {
    position: relative;
    width: 450px;
    background-color: var(--el-fill-color-light);
    overflow: hidden;

    .banner {
      width: 100%;

      @include position-center(y);
    }

    .logo {
      z-index: 9999;
      position: absolute;
      top: 20px;
      left: 20px;
      width: 30px;
      height: 30px;
      border-radius: 4px;
      background: url("../assets/images/logo.png") no-repeat;
      background-size: contain;
      box-shadow: var(--el-box-shadow-light);
    }
  }

  .login-form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    min-height: 500px;
    width: 500px;
    padding: 50px;
    overflow: hidden;

    .title-container {
      position: relative;

      .title {
        font-size: 1.3em;
        color: var(--el-text-color-primary);
        margin: 0 auto 30px;
        font-weight: bold;
      }
    }
  }

  .el-form-item {
    margin-bottom: 24px;

    :deep(.el-input) {
      height: 48px;
      line-height: inherit;
      width: 100%;

      input {
        height: 48px;
      }

      .el-input__prefix,
      .el-input__suffix {
        display: flex;
        align-items: center;
      }

      .el-input__prefix {
        left: 10px;
      }

      .el-input__suffix {
        right: 10px;
      }
    }
  }

  .flex-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;
  }

  .sub-link {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 20px;
    font-size: 14px;
    color: var(--el-text-color-secondary);

    .text {
      margin-right: 10px;
    }
  }
}

.copyright {
  position: absolute;
  bottom: 30px;
  width: 100%;
  margin: 0;
}


.title {
  margin-bottom: 40px !important;
}

.sub-link {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 20px;
  font-size: 14px;
  color: var(--el-text-color-secondary);

  .text {
    margin-right: 10px;
  }
}
</style>

<!--<route lang="yaml">
meta:
title: 新用户注册
constant: true
layout: false
requiresAuth: false
</route>


<script lang="ts" setup>
import { cloneDeep } from 'lodash-es'
import { ElMessage } from 'element-plus'
import { onBeforeMount, reactive, ref } from 'vue'
import apiUser from '@/api/modules/user'

function useFormDialog() {
  const dialogVisible = ref(false)
  const mode = ref<'create' | 'edit'>('create')
  const formModal = reactive<UserApiTypes>({
    id: -1,
    username: '',
    password: '',
  })
  const open = () => {
    dialogVisible.value = true
  }

  const setMode = (type: 'create' | 'edit') => {
    mode.value = type
  }
  const setForm = (source: UserApiTypes) => {
    formModal.id = source.id
    formModal.username = source.username
    formModal.password = source.password
  }
  const clearForm = () => {
    formModal.id = -1
    formModal.username = ''
    formModal.password = ''
  }

  const close = () => {
    dialogVisible.value = false
  }

  return {
    dialogVisible,
    mode,
    open,
    close,
    setMode,
    formModal,
    setForm,
    clearForm,
  }
}

const { open, close, setMode, dialogVisible, mode, formModal, setForm, clearForm } = useFormDialog()

function editUser(row: UserApiTypes) {
  setForm(cloneDeep(row))
  setMode('edit')
  open()
}

function createUser() {
  clearForm()
  setMode('create')
  open()
}

// 获取用户列表
const paginator = reactive({
  page: 1,
  pageSize: 10,
  total: 0,
})
const data = ref<UserApiTypes[]>([])
const loading = ref(true)
function loadAdminUsers() {
  loading.value = true
  apiUser.getList({
    page: paginator.page,
    pageSize: paginator.pageSize,
  }).then((res) => {
    data.value = res.data.list
    paginator.total = res.data.total
  }).finally(() => {
    loading.value = false
  })
}

onBeforeMount(() => {
  loadAdminUsers()
})

// 创建/编辑用户事件
function onCommitForm() {
  if (formModal.username === '') {
    ElMessage({
      type: 'error',
      message: '用户名不能为空',
    })
    return
  }
  if (formModal.password === '') {
    ElMessage({
      type: 'error',
      message: '密码不能为空',
    })
    return
  }
  close()
  loading.value = true
  const apiPromise = mode.value === 'create'
    ? apiUser.add({
      username: formModal.username,
      password: formModal.password,
    })
    : apiUser.edit(formModal)
  apiPromise.then(() => {
    ElMessage({
      type: 'success',
      message: '操作成功',
    })
  }).finally(() => {
    loadAdminUsers()
  })
}

// 删除用户事件
function deleteUser(id: number) {
  loading.value = true
  apiUser.delete(id).then(() => {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
  }).finally(() => {
    loadAdminUsers()
  })
}
</script>

<template>
  <div>
    <PageMain v-loading="loading">
      <el-button type="primary" @click="createUser">
        添加用户
      </el-button>
      <el-table :data="data" stripe>
        <el-table-column prop="id" label="ID" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column label="操作" width="300">
          <template #default="{ row }">
            <el-button type="info" size="small" @click="editUser(row)">
              编辑
            </el-button>

            <el-popconfirm
              v-if="row.role !== 'super'"
              confirm-button-text="确认"
              cancel-button-text="取消"
              confirm-button-type="danger"
              icon-color="#F56C6C"
              title="是否删除该用户"
              @confirm="deleteUser(row.id)"
            >
              <template #reference>
                <el-button type="danger" size="small">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div class="page">
        <el-pagination
          v-model:current-page="paginator.page"
          v-model:page-size="paginator.pageSize"
          layout="sizes, prev, pager, next"
          :total="paginator.total"
          :page-sizes="[5, 10, 20, 50]"
          background
          @current-change="loadAdminUsers()"
          @size-change="loadAdminUsers()"
        />
      </div>
      <el-dialog
        v-model="dialogVisible"
        :title="mode === 'create' ? '添加用户' : '编辑用户'"
        width="100%" style="max-width: 600px;"
      >
        <el-form :model="formModal" label-width="60px">
          <el-row :gutter="20">
            <el-col :xs="24" :md="12">
              <el-form-item label="用户名">
                <el-input v-model="formModal.username" placeholder="请输入用户名" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="12">
              <el-form-item label="密码">
                <el-input v-model="formModal.password" placeholder="请输入密码" type="password" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="close">取消</el-button>
            <el-button type="primary" @click="onCommitForm">
              确认
            </el-button>
          </span>
        </template>
      </el-dialog>
    </PageMain>
  </div>
</template>

<style lang="scss" scoped>
.page {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>


-->
